'use client';
import WebrtcNav from '@/components/WebrtcNav';
import { useEffect, useRef } from 'react';
import { io, Socket } from 'socket.io-client';

export default function Home() {
	const localVideoRef = useRef<HTMLVideoElement | null>(null);
	const remoteVideoRef = useRef<HTMLVideoElement | null>(null);
	const socketRef = useRef<Socket | null>(null);
	const pcRef = useRef<RTCPeerConnection | null>(null);

	useEffect(() => {
		socketRef.current = io('http://localhost:8000/perf/ws');

		socketRef.current.on('offer', async (sdp: any) => {
			if (!pcRef.current) createPeerConnection();
			await pcRef.current!.setRemoteDescription(new RTCSessionDescription(sdp));
			const answer = await pcRef.current!.createAnswer();
			await pcRef.current!.setLocalDescription(answer);
			socketRef.current!.emit('answer', answer);
		});

		socketRef.current.on('answer', async (sdp: any) => {
			await pcRef.current?.setRemoteDescription(new RTCSessionDescription(sdp));
		});

		socketRef.current.on('candidate', async (candidate: any) => {
			try {
				await pcRef.current?.addIceCandidate(new RTCIceCandidate(candidate));
			} catch (err) {
				console.error('Error adding ICE candidate', err);
			}
		});

		return () => {
			socketRef.current?.disconnect();
		};
	}, []);

	const createPeerConnection = async () => {
		pcRef.current = new RTCPeerConnection({
			iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
		});

		pcRef.current.onicecandidate = (event) => {
			if (event.candidate) {
				socketRef.current?.emit('candidate', event.candidate);
			}
		};

		pcRef.current.ontrack = (event) => {
			if (remoteVideoRef.current) {
				remoteVideoRef.current.srcObject = event.streams[0];
			}
		};

		const stream = await navigator.mediaDevices.getUserMedia({
			video: true,
			audio: true,
		});
		if (localVideoRef.current) {
			localVideoRef.current.srcObject = stream;
		}
		stream
			.getTracks()
			.forEach((track) => pcRef.current!.addTrack(track, stream));
	};

	const startCall = async () => {
		if (!pcRef.current) await createPeerConnection();
		const offer = await pcRef.current!.createOffer();
		await pcRef.current!.setLocalDescription(offer);
		socketRef.current?.emit('offer', offer);
	};

	return (
		<div style={{ textAlign: 'center' }}>
			<WebrtcNav text={'Next.js + WebRTC + Socket.IO'}></WebrtcNav>

			<div className="flex gap-4 my-4 justify-center">
				<div className="bg-gray-100">
					<h1 className="text-2xl font-bold border-b bg-gray-500 text-white m-0 py-2">客户端</h1>
					<video ref={localVideoRef} autoPlay playsInline muted width="300" />
				</div>
				<div className="bg-gray-100">
					<h1 className="text-2xl font-bold border-b bg-gray-500 text-white m-0 py-2">服务端</h1>
					<video ref={remoteVideoRef} autoPlay playsInline width="300" />
				</div>
			</div>
			<div className="flex gap-4 my-4 justify-center">
				<button
					onClick={startCall}
					className="bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-700"
				>
					开始呼叫
				</button>
			</div>
		</div>
	);
}
